<template>
  <div class="statistics-container">
    <el-page-header @back="$router.go(-1)" content="广告效果统计" />
    
    <el-card class="filter-card">
      <div class="filter-header">
        <span>统计时段</span>
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="fetchStatisticsData"
        />
      </div>
    </el-card>

    <!-- 核心指标卡片 -->
    <el-row :gutter="20" class="metric-row">
      <el-col :span="6">
        <metric-card title="总播放量" :value="metrics.totalImpressions" icon="View" color="#409EFF"/>
      </el-col>
      <el-col :span="6">
        <metric-card title="总观看量" :value="metrics.totalClicks" icon="Mouse" color="#67C23A"/>
      </el-col>
      <el-col :span="6">
        <metric-card title="平均观看量" :value="metrics.avgCTR" suffix="%" icon="Opportunity" color="#E6A23C"/>
      </el-col>
      <el-col :span="6">
        <metric-card title="消耗预算" :value="metrics.totalCost" prefix="¥" icon="Money" color="#F56C6C"/>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-card class="chart-card">
      <h3>效果趋势分析</h3>
      <div ref="trendChart" style="height: 400px;"></div>
    </el-card>

    <!-- 广告对比图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <h3>广告播放TOP10</h3>
          <div ref="barChart" style="height: 350px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <h3>点击率分布</h3>
          <div ref="pieChart" style="height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import * as echarts from 'echarts/core';
import { LineChart, BarChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DatasetComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import MetricCard from '@/components/MetricCard.vue';
import { getAdStatistics } from '@/api/statistics';

// 注册 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DatasetComponent,
  LineChart,
  BarChart,
  PieChart,
  CanvasRenderer
]);

// 图表DOM引用
const trendChart = ref(null);
const barChart = ref(null);
const pieChart = ref(null);

// 图表实例
let trendInstance = null;
let barInstance = null;
let pieInstance = null;

// 响应式数据
const timeRange = ref([
  dayjs().subtract(30, 'day').format('YYYY-MM-DD'), 
  dayjs().format('YYYY-MM-DD')
]);

const metrics = ref({
  totalImpressions: 0,
  totalClicks: 0,
  avgCTR: 0,
  totalCost: 0
});

// 初始化图表
const initCharts = () => {
  // 确保DOM元素已挂载
  if (trendChart.value) {
    trendInstance = echarts.init(trendChart.value);
  }
  
  if (barChart.value) {
    barInstance = echarts.init(barChart.value);
  }
  
  if (pieChart.value) {
    pieInstance = echarts.init(pieChart.value);
  }
  
  // 添加窗口大小调整监听
  window.addEventListener('resize', handleResize);
};

// 处理窗口大小调整
const handleResize = () => {
  trendInstance?.resize();
  barInstance?.resize();
  pieInstance?.resize();
};

// 获取统计数据
const fetchStatisticsData = async () => {
  try {
    if (!timeRange.value || timeRange.value.length !== 2) {
      ElMessage.warning('请选择完整的日期范围');
      return;
    }

    const params = {
      startTime: timeRange.value[0],
      endTime: timeRange.value[1]
    };
    
    const res = await getAdStatistics(params);
    
    console.log('获取统计数据成功', res);
    // 检查返回数据
    if (res.data.code === 200) {
      const data = res.data.data;
      
      // 更新指标数据
      metrics.value = {
        totalImpressions: data.metrics?.totalImpressions ?? 0,
        totalClicks: data.metrics?.totalClicks ?? 0,
        avgCTR: data.metrics?.avgCTR ?? 0,
        totalCost: data.metrics?.totalCost ?? 0
      };
      
      // 更新图表
      updateTrendChart(data.trend);
      updateBarChart(data.topAds);
      updatePieChart(data.ctrDistribution);
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ElMessage.error('获取统计数据失败');
  }
};

// 更新趋势图配置
const updateTrendChart = (data) => {
  if (!trendInstance) return;
  
  // 检查数据有效性
  if (!data || !data.dates || !data.impressions || !data.clicks || data.dates.length === 0) {
    trendInstance.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center'
      }
    });
    return;
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['展示量', '点击量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '展示量',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.impressions,
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '点击量',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.clicks,
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  };
  
  trendInstance.setOption(option);
};

// 更新柱状图配置
const updateBarChart = (data) => {
  if (!barInstance) return;
  
  // 检查数据有效性
  if (!data || data.length === 0) {
    barInstance.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center'
      }
    });
    return;
  }

  // 提取标题和展示量数据
  const titles = data.map(item => item.title);
  const impressions = data.map(item => item.impressions);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: titles,
      axisLabel: {
        interval: 0,
        rotate: 30,
        formatter: function(value) {
          return value.length > 10 ? value.substring(0, 10) + '...' : value;
        }
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: '展示量',
      type: 'bar',
      barWidth: '60%',
      data: impressions,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#409EFF' },
          { offset: 1, color: '#188df0' }
        ])
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2378f7' },
            { offset: 0.7, color: '#2b85e4' },
            { offset: 1, color: '#4aa3ff' }
          ])
        }
      }
    }]
  };
  
  barInstance.setOption(option);
};

// 更新饼图配置
const updatePieChart = (data) => {
  if (!pieInstance) return;
  
  // 检查数据有效性
  if (!data || data.length === 0) {
    pieInstance.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center'
      }
    });
    return;
  }

  // 将数据转换为饼图需要的格式
  const pieData = data.map(item => ({
    name: item.ctrRange,
    value: item.count
  }));

  // 自定义颜色
  const colorPalette = ['#4FD8FF', '#72CCFF', '#409EFF', '#005EFF'];

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: pieData.map(item => item.name)
    },
    series: [
      {
        name: '点击率分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData,
        color: colorPalette
      }
    ]
  };
  
  pieInstance.setOption(option);
};

// 生命周期钩子
onMounted(() => {
  // 等待DOM更新完成后初始化图表
  setTimeout(() => {
    initCharts();
    fetchStatisticsData();
  }, 100);
});

onBeforeUnmount(() => {
  // 清理图表实例和事件监听
  window.removeEventListener('resize', handleResize);
  trendInstance?.dispose();
  barInstance?.dispose();
  pieInstance?.dispose();
});
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.filter-card {
  margin: 20px 0;
}

.filter-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.metric-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-card h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-row {
  margin-bottom: 20px;
}

/* 添加响应式样式 */
@media (max-width: 768px) {
  .el-col {
    width: 100%;
    margin-bottom: 15px;
  }
  
  .filter-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>